
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../static/css/mainPage.css" th:href="@{/css/mainPage.css}">
    <link rel="stylesheet" href="../static/css/iconfont.css" th:href="@{/css/iconfont.css}">
    <link rel="stylesheet" href="../static/css/searchResult.css" th:href="@{/css/searchResult.css}">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div style="height: 9.5vh; display: flex; justify-content: center; align-items: center; position: relative;background-color: white;width: 100%" th:replace="nav::nav">

</div>
<div class="top-story-container">
    <div class="top-story-main-column">
        <div class="top-story-main-column-card">
            <div class="top-story-main-column-card-head">
<!--                <nav class="top-story-main-column-card-head-nav">-->
<!--                    <a href="http://localhost:8080/mainPageAttention" class="first-a attention-a" ><i class="iconfont iconfont-pattention" style="color: #ff9606;">&#xe602;</i> 关注</a>-->
<!--                    <a href="http://localhost:8080/mainPageRecommend" class="recommend-a" style="color: #0087fe;"><i class="iconfont iconfont-recommend"  style="color: rgb(92, 137, 219);">&#xe628;</i> 推荐</a>-->
<!--                    <a href="http://localhost:8080/mainPageTrending" class="trending-a"><i class="iconfont iconfont-trending" style="color: red;">&#xe603;</i> 热搜</a>-->
<!--                    <a href="mainPageVedio.html" class="vedio-a"><i class="iconfont iconfont-vedio" style="color: rgba(218, 218, 42, 0.608);">&#xe60a;</i> 视频</a>-->
<!--                </nav>-->
                <h3 style="margin-left: 24px">搜索关键字：<span th:text="${keywords}"></span> 的结果</h3>
            </div>
            <div>
                <div class="user-item1" th:if="${users1 != null}" th:each="user: ${users1}">
                    <img src="" alt="用户头像" th:src="${user.avatar}">
                    <div class="user-info1">
                        <span class="username1" th:text="${user.username}">烧饼</span>
                        <span class="tagline" th:text="${user.bio}">世界灿烂盛大，欢迎回家</span>
                        <div class="stats">
                            <span class="answer-count"><span th:text="${user.followerCount}"></span>  粉丝</span> ·
                            <span class="article-count"><span th:text="${user.email}"> 邮箱</span> ·
                            <span class="follower-count"><span th:text="${user.subscription}"></span> 关注者</span>
                        </div>
                    </div>
                    <button class="follow-button" th:classappend="${user.following} ? 'following' : ''">
                        <span th:text="${user.following} ? '取消关注' : '+ 关注她'"></span>
                    </button>
                </div>
            </div>
            <div class="top-story-content-recommend top-story-content" th:if="${posts != null}" th:each="post, postStat : ${posts}" >
                <div class="top-story-content-detail">
                    <a  th:href="@{/posts/select/id?id={id}(id=${post.id})}" style="color: black">
                    <div class="top-story-content-head"><h3 th:text="${post.title}"></h3></div> </a>
                    <div id="content" >
                        <div class="top-story-content-detail-list">
                            <p class="top-story-content-detail-list-p">
                                <a  th:href="@{/posts/select/id?id={id}(id=${post.id})}" style="color: black">
                                   <span class="user-information" th:if="${userStat.index == postStat.index}"  th:each="user, userStat : ${users}">
                                        <img src="../static/img/OIP-C.jpg" alt="" th:src="${user.avatar}">
                                        <span th:text="${user.username}">

                                        </span>
                                        <i class="word-introduction" th:text="${user.bio}">&nbsp;&nbsp;</i>
                                    </span>

                                <i class="user-name" th:if="${userStat.index == postStat.index}"  th:each="user, userStat : ${users}">
                                    <i th:text="${user.username}"></i>
                                    &nbsp;&nbsp;</i>
                                <i class="empty" th:text="${post.content}"> &nbsp;&nbsp;&nbsp;&nbsp;                                  </i></a>
                            </p>
                            <span class="read-full-text"><i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i></span>
                        </div>
                        <div class="content-right">
                            <img  alt="" th:src="${post.imageUrl}"  th:if="${not #strings.isEmpty(post.imageUrl)}"  class="img-content">

                        </div>
                    </div>

                    <div class="top-story-content-footer">
                        <button class="top-story-content-footer-button top-story-content-footer-button-start"  th:value="${post.commentCount}" th:data-value="${post.id}" onclick="articleDetail(this.dataset.value)"><i class="iconfont comment" >&#xe619;</i><span th:text="${post.commentCount}"></span>条评论</button>
                        <button class="top-story-content-footer-button top-story-content-footer-button-share"><i class="iconfont share" >&#xe60e;</i>分享</button>

                        <button class="top-story-content-footer-button top-story-content-footer-button-like" th:value="${post.id}"   th:data-is-liked="${post.isLiked }"  data-type="post"><i class="iconfont like" >&#xe610;</i>喜欢</button>
                        <button class="top-story-content-footer-button top-story-content-footer-button-more">
                            <a  th:href="@{/toReportOthers/?postId={id}(id=${post.id})}" style="color: rgba(169, 178, 185, 0.937);">
                                <i class="iconfont more">&#xe621;</i>
                                举报
                            </a>

                        </button>
                        <div class="share-outer">
                            <div class="share-detail">
                                <i class="iconfont">&#xe618;</i>
                                <span>复制链接</span>
                            </div>
                        </div>
                        <div class="comment-publish">
                            <div class="comment-input-outer">
                                <div class="comment-input">
                                    <input type="text" placeholder="留下你的精彩评论吧"  class="comment-input-detail"  th:data-value="${post.id}">
                                    <div class="input-icons">
                                        <i class="iconfont">&#xe642; </i>
                                        <span class="emoji-icon" th:data-value="${post.id}" onclick="publish(this.dataset.value)"> 发布</span>

                                    </div>
                                </div>
                            </div>

                            <div class="comment-item-outer" th:data-value="${post.id}">

                            </div>


                        </div>
                    </div>
                </div>


            </div>
            <div class="masonry-grid">
                <div  th:each="video, postStat : ${videos}">
                    <div class="masonry-item">
                        <video controls>
                            <source th:src="${video.filePath}" type="video/mp4">
                            您的浏览器不支持视频播放。
                        </video>
                        <a  th:href="@{/videos/select/id?id={id}(id=${video.videoId})}" style="color: black">
                            <p class="title" th:text="${video.title}"></p>
                            <p class="title title-content" th:text="${video.description}"></p>
                            <div th:if="${userStat.index == postStat.index}"  th:each="user, userStat : ${users2}">
                                <div class="author" th:text="${user.username}"></div>
                            </div>
                        </a>
                        <div class="likes" >  <button  class="top-story-content-footer-button top-story-content-footer-button-like"  th:value="${video.videoId}"   th:data-is-liked="${video.isLike }"  data-type="video"><i class="iconfont like" >&#xe610;</i>喜欢</button></div>

                    </div>
                </div>

            </div>

        </div>



    </div>
    <div class="top-story-right-column">
        <div class="creation-center-outer">
            <div class="creation-center-container">
                <div class="creation-center-container-title">
                                <span style="font-size: 15px;">
                                    <i class="iconfont" style="font-size: 21px;">&#xe6c7;</i>
                                    创作中心
                                </span>
                    <span style="font-size: 12px; color:#99a0a7; ;">
                                草稿箱(0)
                               </span>

                </div>
                <div class="creation-center-container-function">

                    <div class="post-vedio">

                        <span class="vedio-span"><i class="iconfont vedio" style="color: #ff9606;">&#xe60a;</i></span>
                        <i>发视频</i>
                    </div>
                    <div class="write-article">

                            <span class="article-span"><i class="iconfont article" style="color: yellowgreen;">&#xe640;</i></span>
                            <i>写文章</i>

                    </div>
                    <div class="write-thought-button">
                            <span class="thought-span"><i class="iconfont thought"
                                                          style="color: rgb(11, 151, 158);">&#xe614;</i></span>
                        <i>写想法</i>

                    </div>
                    <div class="write-thought" style="display: none;">
                        <div class="post-popup">
                            <input type="text" id="titleInput" placeholder="请输入标题 (选填)" maxlength="50">
                            <div class="char-count" id="titleCharCount">0/50</div>
                            <textarea id="contentTextarea" placeholder="分享你此刻的想法..."></textarea>
                            <div class="char-count char-count2" id="contentCharCount">0/300</div>

                            <button id="postButton">发布</button>
                            <div class="close-icon" id="closeButton">&times;</div>
                        </div>

                    </div>
                </div>
                <div class="creation-center-container-prompt">
                    <div class="left">
                        <p>开启你的慧问创作之旅吧</p>
                        <span>即将推出处女作，解锁创作之旅
                                        速来加入慧问创作者行列吧~
                                    </span>
                    </div>
                    <div class="right">

                        <img src="../static/img/可爱的小狗_05_爱给网_aigei_com.gif" alt="" th:src="@{/img/可爱的小狗_05_爱给网_aigei_com.gif}">
                    </div>

                </div>
                <div class="write-outer">
                    <button class="write-button">
                        <i class="iconfont" style="color: rgb(0, 170, 255);">&#xe69a;</i>
                        开始创作
                    </button>
                </div>
            </div>
        </div>
        <div class="carefully-selected-author-outer">
            <div class="carefully-selected-author-container">
                <div class="carefully-selected-author-head"><i class="iconfont">&#xe6df;</i>
                    盐选作者平台</div>
                <div class="carefully-selected-author-body">
                                <span>匠心打磨，丰厚收益<br>
                                    <i>已有60万+作者入驻</i>
                                </span>
                    <span>
                                    <img src="../static/img/金钱(Money)_爱给网_aigei_com.gif" alt="" th:src="@{/img/金钱(Money)_爱给网_aigei_com.gif}">
                                </span>
                </div>
                <div class="carefully-selected-author-button">
                    <button><i class="iconfont">&#xe65d;</i>去投稿</button>
                </div>
            </div>
        </div>


</div>
</div>
</div>
<div class="mask"></div>

<script th:inline="javascript">

    let posts = [[${users2}]];
    let users1 = [[${posts}]];
    let users2 = [[${users1}]];

    console.log(posts)
    console.log(users1)
    console.log(users2)

    const mask=document.querySelector('.mask')
    const titleInput = document.getElementById('titleInput');
    const titleCharCount = document.getElementById('titleCharCount');
    const contentTextarea = document.getElementById('contentTextarea');
    const contentCharCount = document.getElementById('contentCharCount');
    const closeButton = document.getElementById('closeButton');
    const writeThought=document.getElementsByClassName('write-thought')[0]
    const writeThought_button=document.getElementsByClassName('write-thought-button')[0]
    // 标题字数统计
    titleInput.addEventListener('input', function () {
        const charCount = titleInput.value.length;
        titleCharCount.textContent = charCount + '/50';
    });
    contentTextarea .addEventListener('input',function(){
        const charCount=contentTextarea.value.length
        contentCharCount.textContent=charCount+'/300'
    })

    closeButton.addEventListener('click',()=>{
        console.log(closeButton)
        writeThought.style.display='none'
        contentTextarea.value=''
        titleInput.value=''
        document.body.classList.remove('open')
        mask.style.display='none'
    })
    writeThought_button.addEventListener('click',()=>{
        writeThought.style.display='block'
        mask.style.display='block'

        document.body.classList.add('open')
    })

    // 获取所有的 "read-full-text" 元素和 "top-story-content-detail-list-p" 元素
    const read_full_texts = document.getElementsByClassName('read-full-text');
    const top_story_content_detail_list_ps = document.getElementsByClassName('empty');

    // 遍历所有的 "read-full-text" 元素并添加点击事件监听器
    for (let i = 0; i < read_full_texts.length; i++) {
        read_full_texts[i].addEventListener('click', function() {
            const index = Array.from(read_full_texts).indexOf(this);
            const targetParagraph = top_story_content_detail_list_ps[index];
            const user_information=document.getElementsByClassName('user-information')[index]
            const empty=document.getElementsByClassName('empty')[index]
            const user_name=document.getElementsByClassName('user-name')[index]
            const contentright=contentrights[index]
            const top_story_content_detail_list=top_story_content_detail_lists[index]
            // 使用 window.getComputedStyle 获取元素的实际样式
            const currentHeight = window.getComputedStyle(targetParagraph).height;
            if (currentHeight === '49px') {
                targetParagraph.style.height = 'auto';
                targetParagraph.style.display= 'block';
                user_information.style.display='block'
                user_name.style.display='none'
                empty.classList.add('content')
                contentright.style.display='none'
                console.log(contentright.style.display)
                console.log(1)
                top_story_content_detail_list.style.width='100%'
                this.innerHTML = '<i class="iconfont">&#xe60d;</i>收起<i class="iconfont">&#xe6b8;</i>';
            } else {
                targetParagraph.style.height = '49px';
                this.innerHTML = '<i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i>';
                targetParagraph.style.display= '-webkit-box';
                user_information.style.display='none'
                user_name.style.display='inline'
                empty.classList.remove('content')
                contentright.style.display='block'
                top_story_content_detail_list.style.width='74%'
            }
        });
    }

    //
    const contentrights=document.getElementsByClassName('content-right')
    const top_story_content_detail_lists=document.getElementsByClassName('top-story-content-detail-list')
    let personalMainPage=document.getElementsByClassName('personalMainPage')[0]
    console.log(personalMainPage)
    personalMainPage.addEventListener('click',()=>{
        event.preventDefault();
        window.location.href='http://localhost:8080/userHomepage'
    })
    let write_button=document.getElementsByClassName('write-button')[0]
    write_button.addEventListener('click',()=>{
        window.location.href='http://localhost:8080/creativeCenter'
    })
    let mainPage=document.getElementsByClassName('mainPage')[0]
    mainPage.addEventListener('click',()=>{
        event.preventDefault();
        window.location.href='http://localhost:8080/mainPageRecommend'
    })
    const write_article=document.getElementsByClassName('write-article')[0]
    write_article.addEventListener('click',()=>{
        window.location.href = "http://localhost:8080/postArticle";
    })
    const post_vedio=document.getElementsByClassName('post-vedio')[0]
    post_vedio.addEventListener('click',()=>{
        window.location.href = "http://localhost:8080/vedio";
    })

    let top_story_content_footer_button_likes=document.getElementsByClassName('top-story-content-footer-button-like')
    let likes=document.getElementsByClassName('like')
    for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
        top_story_content_footer_button_likes[i].addEventListener('click', function () {
            const parentClass = this.closest('.top-story-content-recommend')? 'post' : 'video';

            let like_value=top_story_content_footer_button_likes[i].value
            const postIdNum = Number(like_value);
            console.log(postIdNum)
            console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
            if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)'&&parentClass === 'post') {

                $.ajax({
                    url: `/posts/like?postId=${like_value}`,

                    type: 'POST',
                    data: {postId: postIdNum},
                    success: function (result) {
                        showCustomAlert('点赞成功', 3000)
                        console.log(top_story_content_footer_button_likes[i].dataset.isLiked)
                        top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                        likes[i].style.color= 'rgba(255,0,0,1)'
                        // top_story_content_footer_button_likes[i].dataset.isLiked++;
                        console.log(  top_story_content_footer_button_likes[i].style.color)
                        console.log('发送点赞请求到:', this.url);
                        console.log('我是帖子点赞')
                    },
                    error: function (error) {
                        showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                        console.log(error);
                        console.log('发送点赞请求到:', this.url);
                    }

                })

            }else if(parentClass === 'post'&&  top_story_content_footer_button_likes[i].style.color === 'rgb(255, 0, 0)') {
                console.log(1111111)
                $.ajax({
                    url: `/posts/cancelLike?postId=${like_value}`,

                    type: 'POST',
                    data: {postId: postIdNum},
                    success: function (result) {
                        showCustomAlert('取消点赞', 3000)
                        // top_story_content_footer_button_likes[i].dataset.isLiked--;
                        top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                        likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                        console.log('发送点赞请求到:', this.url);
                    },
                    error: function (error) {
                        showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                        console.log(error);
                        console.log('发送点赞请求到:', this.url);
                    }

                })
            }

        })
    }
    function articleDetail(postId) {
        const postIdNum = Number(postId);
        const comment_item_outers = document.getElementsByClassName('comment-item-outer');
        let comment_item_outer;
        for(let i=0;i<comment_item_outers.length;i++){
            if(comment_item_outers[i].dataset.value===postId){
                comment_item_outer=comment_item_outers[i];
                console.log(comment_item_outers[i].value)
                console.log(comment_item_outer)
            }
        }

        comment_item_outer.innerHTML = '';
        currentPage=1;
        totalCommentsCount=0;

        // 初始化加载第一页
        loadComments(postIdNum,currentPage);


    }

    let comments=document.getElementsByClassName('comment-publish')
    let top_story_content_footer_button_starts=document.getElementsByClassName('top-story-content-footer-button-start')
    for(let i=0;i<top_story_content_footer_button_starts.length;i++){
        top_story_content_footer_button_starts[i].addEventListener('click',()=>{
            if( top_story_content_footer_button_starts[i].innerHTML.includes('收起评论')){
                comments[i].style.display='none'
                let value=top_story_content_footer_button_starts[i].value
                top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> ${value}条评论`
            }else{
                top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> 收起评论`
                comments[i].style.display='block'
            }





        })
    }


    function publish(postId) {
        currentPostId = Number(postId);
        let comment_input_detail;
        let content;
        let comment_input_details = document.getElementsByClassName('comment-input-detail');
        for(let i=0;i<comment_input_details.length;i++){
            if( comment_input_details[i].dataset.value===postId){
                comment_input_detail=comment_input_details[i]
                content = comment_input_detail.value;
                console.log(content)
                console.log(comment_input_detail)
            }
        }

        $.ajax({
            url: `/posts/comment`,
            type: 'POST',
            data: {postId: currentPostId, content: content},
            success: function(result) {
                showCustomAlert('评论成功', 3000);
                console.log(result);
                comment_input_detail.value = '';

                // 重置分页状态，重新加载评论
                currentPage = 1;
                hasMoreData = true;

                // 清空现有评论，加载第一页
                let comment_item_outer;
                let  comment_item_outers = document.getElementsByClassName('comment-item-outer');
                for(let i=0;i<comment_item_outers.length;i++){
                    if( comment_item_outers[i].dataset.value===postId){
                        comment_item_outer =comment_item_outers[i]


                    }
                }
                comment_item_outer.innerHTML = '';
                loadComments(currentPostId, currentPage);

            },
            error: function(error) {
                showCustomAlert('评论失败: ' + error.status + ' ' + error.statusText, 3000);
                console.log(error);
            }
        });



    }
    // 加载评论函数

    function loadComments(postIdNum,page) {
        isLoading = true;
        $.ajax({
            url: `/postsComments?postId=${postIdNum}&pageNum=${page}`,
            type: 'GET',
            success: function(result) {
                const id = result.userId;
                const comments = result.comments;
                const commentUsers = result.commentUsers;
                totalPages = result.totalPages; // 更新总页数
                // **更新累计评论数**
                // totalCommentsCount += comments.length;
                console.log(result)
                console.log(id)
                // 首次加载时初始化列表

                let commentListHTML = comments.length === 0 ?
                    '<div class="empty-comment" xmlns="http://www.w3.org/1999/html"><i class="iconfont cat">&#xe61c;</i><br><span >暂无评论</span></div>' :
                    comments.map((comment, i) => `
                            <div class="comment-item" style="padding-top: 10px;">
                                <div class="comment-user">
                                    <img src="${commentUsers[i].avatar}" alt="用户头像" class="avatar">
                                    <span class="username">${commentUsers[i].username}</span>
                                </div>
                                <div class="comment-content" data-value="${commentUsers[i].userId}">
                                    <p>${comment.content}</p>
                                    <span class="comment-time">${comment.createdAt}</span>
                                </div>
                                <div class="comment-actions">
                                    <span class="reply-icon" data-value="${comment.id}"><i class="iconfont comment-delete comment_like_icon">&#xe653;</i>点赞</span>
                                    <span class="share-icon2" data-value="${comment.id}"><i class="iconfont comment-delete">&#xe63f;</i>删除</span>
                                </div>
                            </div>
                        `).join('');
                const string=`<div class="detail-comment">进入详情页查看全部评论~</div>`
                const comment_item_outers = document.getElementsByClassName('comment-item-outer');
                let comment_item_outer;
                for(let i=0;i<comment_item_outers.length;i++){
                    if(Number(comment_item_outers[i].dataset.value)===postIdNum){
                        comment_item_outer=comment_item_outers[i];
                    }
                }

                if (page === 1) {

                    comment_item_outer.innerHTML = commentListHTML; // 替换内容
                    comment_item_outer.innerHTML+=string;
                }



                const pageSize = 5; // 根据后端接口设置
                const startIndex = (page - 1) * pageSize;
                const endIndex = page * pageSize - 1;

                const allShareIcons = document.getElementsByClassName('share-icon2');
// 提取当前页的删除按钮（基于页码和每页条数）
                const currentPageShareIcons = Array.from(allShareIcons).slice(startIndex, endIndex + 1);
                const replyIcons = document.getElementsByClassName('reply-icon');
                const commentLikeIcons = document.getElementsByClassName('comment_like_icon');
                console.log(commentUsers)

                for (let i = 0; i < comments.length; i++) {
                    const commentUser = commentUsers[i];

                    console.log(commentUser.id)
                    if (String(id) === String(commentUser.id)) {
                        const shareIcon = currentPageShareIcons[i]; // 当前页内的相对索引
                        console.log(shareIcon)
                        shareIcon.style.display = 'block';
                        console.log(1111)
                    }
                }

                // 绑定删除事件
                Array.from(currentPageShareIcons).forEach(shareIcon => {
                    shareIcon.addEventListener('click', () => {
                        const commentId = Number(shareIcon.dataset.value);
                        console.log(commentId)
                        $.ajax({
                            url: `/posts/comment/user`,
                            type: 'POST',
                            data: { commentId:commentId },
                            success: (result) => {
                                showCustomAlert('删除成功', 3000);
                                totalCommentsCount = 0;
                                // 删除后重新加载当前页（可选：优化为局部删除）
                                if (comments.length === 0 && currentPage > 1) {
                                    currentPage--;
                                    // 重新加载上一页
                                }
                                loadComments(postIdNum, currentPage);
                            },
                            error: (error) => {
                                showCustomAlert('删除失败: ' + error.statusText, 3000);
                            }
                        });
                    });
                });

                // 绑定点赞事件
                Array.from(replyIcons).forEach((replyIcon, i) => {
                    replyIcon.addEventListener('click', () => {
                        const commentId = Number(replyIcon.dataset.value);
                        if (replyIcon.style.color === 'red') {
                            // 取消点赞
                            $.ajax({
                                url: `/comments/cancelLike`,
                                type: 'POST',
                                data: { commentsId: commentId },
                                success: () => {
                                    showCustomAlert('取消点赞成功', 3000);
                                    commentLikeIcons[i].style.color = 'rgb(82, 91, 100)';
                                    replyIcon.style.color = 'rgb(82, 91, 100)';
                                }
                            });
                        } else {
                            // 点赞
                            $.ajax({
                                url: `/comments/like`,
                                type: 'POST',
                                data: {commentsId: commentId  },
                                success: () => {
                                    showCustomAlert('点赞成功', 3000);
                                    commentLikeIcons[i].style.color = 'red';
                                    replyIcon.style.color = 'red';
                                }
                            });
                        }
                    });
                });

                // 初始化点赞状态
                comments.forEach((comment, i) => {
                    if (comment.isLiked) {
                        commentLikeIcons[i].style.color = 'red';
                        replyIcons[i].style.color = 'red';
                    }
                });

                isLoading = false; // 加载完成
            },
            error: (error) => {
                currentPage--; // 加载失败时回退页码
                isLoading = false;
                showCustomAlert('加载评论失败: ' + error.statusText, 3000);
            }
        });


    }
    const likeButton = document.getElementsByClassName('top-story-content-footer-button-like');
    const like=document.getElementsByClassName('like')
    console.log(likeButton)
    for(let i=0;i<likeButton.length;i++){
        // 获取 data-is-liked 的值
        const isLikedValue = likeButton[i].dataset.isLiked;
        console.log(likeButton[i])
        console.log(isLikedValue)
        if(Number(isLikedValue)){
            likeButton[i].style.color='rgba(255,0,0,1)'
            like[i].style.color='rgba(255,0,0,1)'
            console.log(11111111111)
        }
    }

    function showCustomAlert(message, duration) {
        let customAlert = document.getElementById('customAlert');
        if (!customAlert) {
            div_outter=document.createElement('div');
            customAlert = document.createElement('div');
            customAlert.id = 'customAlert';
            // customAlert.style.margin='7px 12px';
            const alertMessage = document.createElement('p');
            alertMessage.id = 'alertMessage';
            customAlert.appendChild(alertMessage);

            document.body.appendChild(customAlert);
        }

        const alertMessage = document.getElementById('alertMessage');

        alertMessage.textContent = message;
        if(alertMessage.textContent==null){
            customAlert.style.display = 'none';
        }

        customAlert.style.display = 'block';
        setTimeout(() => {
            customAlert.style.display = 'none';
        }, duration);
    }

    for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
        top_story_content_footer_button_likes[i].addEventListener('click', function () {
            const parentClass = this.closest('.top-story-content-recommend')? 'post' : 'video';


            let like_value=top_story_content_footer_button_likes[i].value
            const postIdNum = Number(like_value);
            console.log(postIdNum)
            console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
            if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)'&&parentClass === 'video') {

                $.ajax({
                    url: `/videos/like?videoId=${like_value}`,

                    type: 'POST',
                    data: {videoId: postIdNum},
                    success: function (result) {
                        showCustomAlert('点赞成功', 3000)
                        console.log('post')
                        top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                        likes[i].style.color= 'rgba(255,0,0)'
                        // top_story_content_footer_button_likes[i].dataset.isLiked++;
                        console.log(top_story_content_footer_button_likes[i].dataset.isLiked)
                        console.log('发送点赞请求到:', this.url);
                    },
                    error: function (error) {
                        showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                        console.log(error);
                        console.log('发送点赞请求到:', this.url);
                    }

                })

            }else if(parentClass === 'video'&&window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgb(255, 0, 0)'){
                console.log(1111111)
                $.ajax({
                    url: `/videos/cancelLike?videoId=${like_value}`,

                    type: 'POST',
                    data: {videoId: postIdNum},
                    success: function (result) {
                        showCustomAlert('取消点赞', 3000)
                        // top_story_content_footer_button_likes[i].dataset.isLiked--;
                        top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                        likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                        console.log('取消点赞成功')
                    },
                    error: function (error) {
                        showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                        console.log(error);
                        console.log('发送点赞请求到:', this.url);
                    }

                })
            }

        })
    }
    // let top_story_content_footer_button_likes = document.getElementsByClassName('top-story-content-footer-button-like');
    //
    // for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
    //     console.log('进入for循环')
    //     top_story_content_footer_button_likes[i].addEventListener('click', function () {
    //         console.log('进入点击函数')
    //         const button = this;
    //         const type = button.dataset.type; // 获取类型（post/video）
    //         const likeValue = button.value;
    //         const isLiked = button.dataset.isLiked === 'true'; // 注意布尔值判断
    //         const isDefaultColor = window.getComputedStyle(button).color === 'rgba(169, 178, 185, 0.937)';
    //
    //         // 根据类型确定请求 URL
    //         const likeUrl = type === 'post' ? '/posts/like' : '/videos/like';
    //         const cancelLikeUrl = type === 'post' ? '/posts/cancelLike' : '/videos/cancelLike';
    //
    //         if (isDefaultColor && !isLiked) {
    //             console.log('进入点赞函数')
    //             // 点赞
    //             $.ajax({
    //                 url: likeUrl,
    //                 type: 'POST',
    //                 data: { [type === 'post' ? 'postId' : 'videoId']: likeValue },
    //                 success: function (result) {
    //                     showCustomAlert('点赞成功', 3000);
    //                     button.style.color = 'rgba(255, 0, 0, 1)';
    //                     button.dataset.isLiked = 'true'; // 更新状态
    //                 },
    //                 error: function (error) {
    //                     showCustomAlert('点赞失败', 3000);
    //                 }
    //             });
    //         } else if (!isDefaultColor && isLiked) {
    //             console.log('进入取消点赞函数')
    //             // 取消点赞
    //             $.ajax({
    //                 url: cancelLikeUrl,
    //                 type: 'POST',
    //                 data: { [type === 'post' ? 'postId' : 'videoId']: likeValue },
    //                 success: function (result) {
    //                     showCustomAlert('取消点赞', 3000);
    //                     button.style.color = 'rgba(169, 178, 185, 0.937)';
    //                     button.dataset.isLiked = 'false'; // 更新状态
    //                 },
    //                 error: function (error) {
    //                     showCustomAlert('取消点赞失败', 3000);
    //                 }
    //             });
    //         }
    //     });
    // }
    let wait_answer=document.getElementsByClassName('wait-answer')[0]
    console.log(wait_answer)
    wait_answer.addEventListener('click',()=>{
      event.preventDefault();
      window.location.href='/thoughtMainPage'
    })
</script>
</body>

<!--<script src="../static/js/mainPageRecommend.js" th:src="@{/js/mainPageRecommend.js}"></script>-->
<!--<script src="../static/js/video.js" th:src="@{/js/video.js}"></script>-->
<!--<script src="../static/js/mainPageVideo.js" th:src="@{/js/mainPageVideo.js}"></script>-->
</html>